<?php
/**
 * Created by PhpStorm.
 * User: dolia
 * Date: 2016/4/5
 * Time: 17:20
 */

namespace App\Http\Controllers\Api\V1;


use App\Exceptions\Api\ApiDoneErrorException;
use App\Exceptions\Api\ApiInputErrorException;
use App\Exceptions\Api\ApiRsaEecryptErrorException;
use App\Exceptions\Api\ApiUserNotLoginErrorException;
use App\Exceptions\Api\ApiValidateErrorException;
use App\Http\Controllers\Controller;
use App\Interfaces\CollectionService;
use App\Http\Requests;
use App\Interfaces\GoodsService;
use App\Interfaces\ShopService;
use App\Interfaces\UserCollectionService;
use App\Http\Requests\Api\ApiRequest as Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

class CollectionController extends Controller{

    /**
     * @api {post} /collection 根据收藏类型获取收藏
     * @apiName Collection/index
     * @apiGroup Collection
     * @apiDescription 根据收藏类型获取收藏
     * @apiParam {string} type 收藏类型（GOODS(商品)|SHOP(店铺)）
     * @apiParam {int} [page]  第几页
     * @apiSuccess {Object} Object 收藏信息
     * @apiSuccess {Object[]}  Object.data   商品信息|店铺信息
     * @apiSuccess {Object[]}  Object.data.goods   店铺商品信息
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     // GOODS(商品)
    {
    "total": 1,
    "per_page": 1,
    "current_page": 1,
    "last_page": 1,
    "next_page_url": null,
    "prev_page_url": null,
    "from": 1,
    "to": 1,
    "data": [
    {
    "goods_id": 2633,
    "cat_id": 425,
    "goods_sn": "BYJ000003",
    "goods_bar_code": null,
    "goods_name": "德拉克  小麦啤酒  500ml",
    "goods_pet_name": "亲朋好友聚会必备",
    "goods_desc": "德国 Durlacher 德拉克小麦啤酒，是爱士堡2011年在中国区最新推出的主打品牌，也是爱士堡最具特色的啤酒产品之一，清澈透明，富有光泽，泡沫细腻结白，持久而厚实，劲爽甘冽，纯正清香精选优质纯麦芽酿造，啤酒花，山泉水不添加任何杂粮，确保啤酒麦香浓郁，口感纯正。原麦汁浓度11.8°P，酒精度：5.3°。",
    "brand_id": 454,
    "goods_number": 0,
    "goods_weight": "0.000",
    "market_price": "11.00",
    "shop_price": "8.90",
    "keywords": "德拉克,小麦啤酒,500ml",
    "goods_content": "<p><img alt=\"20160215_112146_047.jpg\" src=\"http://afyg.img-cn-qingdao.aliyuncs.com/83680f42e930626a2de602476eb75d86.jpg\" width=\"850\" height=\"787\"><img alt=\"20160215_112146_048.jpg\" src=\"http://afyg.img-cn-qingdao.aliyuncs.com/3d7aa8c280f209b794157bbbc39814b8.jpg\" width=\"850\" height=\"839\"><img alt=\"20160215_112146_049.jpg\" src=\"http://afyg.img-cn-qingdao.aliyuncs.com/60fb452e7a7fe8deeab2cb8e5ef6e25c.jpg\" width=\"850\" height=\"572\"><img alt=\"20160215_112146_050.jpg\" src=\"http://afyg.img-cn-qingdao.aliyuncs.com/dd39d9e3effa881038be45b68a241012.jpg\" width=\"850\" height=\"794\"><img alt=\"20160215_112146_051.jpg\" src=\"http://afyg.img-cn-qingdao.aliyuncs.com/62908a1b3dfe64cc87d96305d414eac1.jpg\" width=\"850\" height=\"768\"><img alt=\"20160215_112146_053.jpg\" src=\"http://afyg.img-cn-qingdao.aliyuncs.com/24aa9ad34706b78bb1e776f61b265a8f.jpg\" width=\"850\" height=\"775\"><br></p>",
    "goods_thumb": "f5917635ce41ace5189b36c9edcc3632",
    "resource": "德国",
    "type": 0,
    "goods_gallery_id": 0,
    "is_on_sale": 1,
    "add_time": 0,
    "sort_order": 100,
    "is_delete": 0,
    "is_home_recommend": 0,
    "is_cat_recommend": 0,
    "shop_id": 12,
    "sales_num": 0,
    "deleted_at": null,
    "search_keywords": "德拉克,小麦啤酒,500ml,德拉克,进口美食,饮料、酒水、茶叶,酒水饮料,酒水,饮料,酒水,酒,酒水",
    "created_at": "2016-02-15 11:30:41",
    "updated_at": "2016-02-21 13:17:36",
    "audit_status": 1,
    "mobile_goods_content": "",
    "mobile_goods_thumb": "http://dolia.img-cn-hangzhou.aliyuncs.com/f5917635ce41ace5189b36c9edcc3632.jpg"
    }
    ]
    }
    //SHOP(店铺)
    {
    "total": 1,
    "per_page": 15,
    "current_page": 1,
    "last_page": 1,
    "next_page_url": null,
    "prev_page_url": null,
    "from": 1,
    "to": 1,
    "data": [
    {
    "id": 5,
    "shop_name": "阿福易购",
    "shop_logo": "cae871cec556d714de993401961d9619",
    "shop_desc": "阿福易购",
    "sort_order": 0,
    "is_show": 0,
    "mobile_shop_logo": "http://dolia.img-cn-hangzhou.aliyuncs.com/cae871cec556d714de993401961d9619.png"
    "goodsNum": 1050,
    "goods": [
        {
        "goods_id": 105,
        "cat_id": 417,
        "goods_sn": "af000098",
        "goods_bar_code": "8806154843171",
        "goods_name": "贝尊Babyprime 杰奎琳小米枕头 粉色",
        "goods_pet_name": "用心关爱 给宝宝最大的关怀",
        "goods_desc": "枕头套100%棉/填充物100%小米，降低宝宝的体温，确保宝宝好睡眠。",
        "brand_id": 63,
        "goods_number": 10,
        "goods_weight": "0.000",
        "market_price": "158.00",
        "shop_price": "106.00",
        "keywords": "枕头,婴儿枕头",
        "goods_content": "",
        "goods_thumb": "c1222e02c470b7b6a7b3c4c312646a1d",
        "resource": "韩国",
        "type": 1,
        "goods_gallery_id": 0,
        "is_on_sale": 1,
        "add_time": 0,
        "sort_order": 100,
        "is_delete": 0,
        "is_home_recommend": 0,
        "is_cat_recommend": 0,
        "shop_id": 5,
        "sales_num": 0,
        "deleted_at": null,
        "search_keywords": "枕头,婴儿枕头,贝尊 Babyprime,母婴用品,母婴用品,宝宝用品,宝宝,婴儿,宝宝家居,宝宝,家居",
        "created_at": "2016-01-15 12:00:00",
        "updated_at": "2016-03-22 09:38:58",
        "audit_status": 1,
        "mobile_goods_thumb": "http://afutest.img-cn-qingdao.aliyuncs.com/c1222e02c470b7b6a7b3c4c312646a1d.jpg"
        }
    ]
    }
    ]
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 403 Forbidden
    {
    "message": "请先登录"
    }
     * @apiErrorExample Error-Response 02:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数type"
    }
     */
    public function index(Request $request, CollectionService $collectionService,GoodsService $goodsService,ShopService $shopService){


        $user_id = $request->apiUser->get()->id;
        $type = $request->get('type');

        if($user_id==''){
            throw new ApiUserNotLoginErrorException('请先登录');
        }
        if($type==''){
            throw new ApiInputErrorException('缺少请求参数type');
        }

        $data = [];
        if($type=='GOODS'){
            $collection = $collectionService->getUserCollectionByType($user_id,$type)->toArray();
            $collectionGoods = $collection['data'];
            for($i=0,$j=0;$i<count($collectionGoods);$i++){
                if($goodsService->get($collectionGoods[$i]['reference_id'])){
                    $data[$j] = $goodsService->get($collectionGoods[$i]['reference_id'])->toArray();
                    $j++;
                }
            }

        }
        if($type=='SHOP'){
            $collection = $collectionService->getUserCollectionByType($user_id,$type)->toArray();
            $collectionShop = $collection['data'];
            for($i=0,$j=0;$i<count($collectionShop);$i++){
                if($shopService->get($collectionShop[$i]['reference_id'])){
                    $shops = $shopService->get($collectionShop[$i]['reference_id'])->toArray();
                    $countGoods = $goodsService->countGoodsByShop($shops['id']);
                    $data[$j] = $shops;
                    $data[$i]['goodsNum'] = $countGoods;
                    $data[$i]['goods'] = $goodsService->getShopGoods($data[$i]['id'])->take(6)->toArray();
                    $j++;
                }
            }

        }

        $page = $request->get('page') ?: Paginator::resolveCurrentPage('page');
        $paginate =  new LengthAwarePaginator($data, count($data), 15, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);

        return response()->json($paginate->toArray());
    }


    /**
     * @api {post} /collection/add 添加收藏
     * @apiName Collection/add
     * @apiGroup Collection
     * @apiDescription 添加收藏
     * @apiParam {string} type 收藏类型（GOODS(商品)|SHOP(店铺)）
     * @apiParam {int} id 收藏的关联ID
     * @apiSuccess {Object[]} Object 收藏信息
     * @apiSuccess {int} Object.id 收藏ID
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "id": 38
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 403 Forbidden
    {
    "message": "请先登录"
    }
     * @apiErrorExample Error-Response 02:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数type"
    }
     * @apiErrorExample Error-Response 03:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数id"
    }
     * @apiErrorExample Error-Response 04:
     * HTTP/1.1 202 Accepted
    {
    "message": "已收藏"
    }
     */
    public function add(Request $request,UserCollectionService $userCollectionService){
        $user_id = $request->apiUser->get()->id;
        $type = $request->get('type');
        $id = $request->get('id');
        if($user_id==''){
            throw new ApiUserNotLoginErrorException('请先登录');
        }
        if($type==''){
            throw new ApiInputErrorException('缺少请求参数type');
        }
        if($id==''){
            throw new ApiInputErrorException('缺少请求参数id');
        }
        $addCollection = $userCollectionService->add($user_id,$type,$id);
        if($addCollection){
            return response()->json(['id'=>$addCollection->id]);
        }else{
            throw new ApiDoneErrorException('已收藏');
        }
    }

    /**
     * @api {post} /collection/cancel 取消收藏
     * @apiName Collection/cancel
     * @apiGroup Collection
     * @apiDescription 取消收藏
     * @apiParam {string} type 收藏类型（GOODS(商品)|SHOP(店铺)）
     * @apiParam {int} id 收藏的关联ID
     * @apiSuccess {Object[]} Object 收藏信息
     * @apiSuccess {int} Object.id 收藏ID
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
    {
    "id": 38
    }
     * @apiErrorExample Error-Response 01:
     * HTTP/1.1 403 Forbidden
    {
    "message": "请先登录"
    }
     * @apiErrorExample Error-Response 02:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数type"
    }
     * @apiErrorExample Error-Response 03:
     * HTTP/1.1 400 Bad Request
    {
    "message": "缺少请求参数id"
    }
     * @apiErrorExample Error-Response 04:
     * HTTP/1.1 202 Accepted
    {
    "message": "取消收藏失败"
    }
     */
    public function cancel(Request $request,UserCollectionService $userCollectionService){
        $user_id = $request->apiUser->get()->id;
        $type = $request->get('type');
        $id = $request->get('id');
        if($user_id==''){
            throw new ApiInputErrorException('请先登录');
        }
        if($type==''){
            throw new ApiInputErrorException('缺少请求参数type');
        }
        if($id==''){
            throw new ApiInputErrorException('缺少请求参数id');
        }
        $cancelCollection = $userCollectionService->cancel($user_id,$type,$id);
        if($cancelCollection ){
            return response()->json(['id'=>$id]);
        }else{
            throw new ApiDoneErrorException('取消收藏失败');
        }
    }



}